<?php

use Biz\model\store\StoreAccount as mAccount;
use Biz\service\Store\VirtualPhone;
use Biz\cache\store\StoreCallAndReserve;
use Biz\model\store\StoreOperator;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\otherRedis;

/**
 * 获取用户和门店AXB之间的虚拟手机号
 *
 */
class GetVirtualPhoneAction extends ActionPlugin
{
    const DEFAULT_ERROR_CODE = self::CODE_ERROR_VIEW_TOSTA;

    public const USER_LEVEL = self::LEVEL_REGISTER;

    public const VALIDATOR_RULES = [
        'store_id' => 'require|integer',
        'user_phone' => 'require|number',
    ];

    public function main()
    {

        $store_id = $this->params['store_id'];
        $user_phone = $this->params['user_phone'];

        $account_info = mAccount::getInfoByWhere(['store_id' => $store_id]);
        $official_phone = null;
        if($account_info && is_array($account_info)){
            $store_operator = StoreOperator::getInfoByAid($account_info['id']);
            if($store_operator && is_array($store_operator)){
                $official_phone = $store_operator['phone'];
            }
        }

        //两个手机号必须都有值才能调用生成虚拟手机号码
        if (empty($official_phone) || empty($user_phone)) {
            throw new \Exception("抱歉,虚拟号业务同时需要两方手机号才能生成!!", self::DEFAULT_ERROR_CODE);
        }
        //调用虚拟手机号业务,生成虚拟手机号
        $virtual_info = VirtualPhone::createVirtualPhone($official_phone, $user_phone, $store_id, $this->uid,
            VirtualPhone::POOL_KEY, VirtualPhone::DIRECTION_UXO);
        if (empty($virtual_info)) {
            throw new \Exception("网络有点慢，请重试!", self::DEFAULT_ERROR_CODE);
        }
        $virtual_phone = $virtual_info['virtual_phone'];
        $virtual_expire_time = $virtual_info['virtual_expire_time'];
        //处理返回的数据
        $data = [
            "virtual_phone" => $virtual_phone,
            "virtual_expire_time" => $virtual_expire_time,
        ];

        //处理手机号后记录该用户的拨打次数至缓存
        StoreCallAndReserve::setUserCallStore($this->uid, $store_id);

        //迁移
//        $constKey = redisKeys::KEY_B_OTHER_USER_STORE_CALL_;
//        $redis = new otherRedis($constKey);
//        $key = $constKey.$this->uid;
//
//        $redis->sadd($key,$store_id);
//        $end_time =  strtotime(date('Y-m-d')) + 86400;
//        $redis->expireat($key,$end_time);


        $this->setSuccess($data);
    }
}